var redis = require('redis');
var EventProxy = require('eventproxy');
var logger = require('../service/Logger');
var config = require('../config').config;
var client = redis.createClient('6379', '127.0.0.1');
    client.on("error", function(error) {
        logger.debug(error);
    });
    client.auth('aFu1hvCV5ks1G9jjx5J8');
    logger.debug('connected to redis cache!');

/**
 * get wechat access
 * @param params
 * @param callback
 */
exports.getAccesstoken = function (callback){
    client.auth(config.redis_password);
    var key = 'fanju_wechat:accesstoken';
    client.get(key, function (err, obj) {
        callback(err, obj);
    });
}

exports.saveAccesstoken = function(token, callback){
    client.auth(config.redis_password);
    var key = 'fanju_wechat:accesstoken';
    client.set(key, token, function (err, obj) {
        callback(err, obj);
    });
}
/**
 * 获得一个user
 * @param openid
 * @param callback
 */
exports.getUser = function(openid, callback){
    client.auth(config.redis_password);
    var key = 'user:openid:'+openid;
    client.hgetall(key, function (err, obj) {
        callback(err, obj);
    });
}
/**
 * 获得一个user
 * @param userid
 * @param callback
 */
exports.getUserById = function(userid, callback){
    client.auth(config.redis_password);
    var key = 'user:id:'+userid;
    client.hgetall(key, function (err, obj) {
        callback(err, obj);
    });
}
/**
 * 更新user
 * @param openid
 * @param field
 * @param value
 * @param callback
 */
exports.updateUser = function(openid, field, value, callback){
    client.auth(config.redis_password);
    var key = 'user:openid:'+openid;
    client.hset(key, field, value, function (err, obj) {
        callback(err, obj);
    });
}
/**
 * 逻辑删除缓存user
 * @param openid
 * @param callback
 */
exports.removeUser = function(openid, callback){
    client.auth(config.redis_password);
    var key = 'user:openid:'+openid;
    client.hdel(key, 'id', 'openid', function(err, obj){
        callback(err, obj);
    });
}

/**
 * 缓存user user:openid:
 *         user:id:
 * @param user
 */
exports.putUserIntoCache = function(user, callback){
    var ep = new EventProxy();
    ep.bind('error', function(err){
        if(err)
            ep.unbind();
        callback(err)
    });
    ep.all('openId', 'userId', function(openId, userId){
        console.log(openId + '===' + userId);
        callback(null, {});
    });
    client.auth(config.redis_password);
    var key = 'user:openid:'+user.openid;
    _setHashSet(key, user, function(err, obj){
        if(err) return ep.emit('error', err);
        ep.emit('openId', obj)
    });
    var key2 = 'user:id:'+user._id;
    _setHashSet(key2, user, function(err, obj){
        if(err) return ep.emit('error', err);
        ep.emit('userId', obj)
    });
}
function _setHashSet(key, user, fn){
    client.hmset(key,
        'id', user._id,
        'openid', user.openid,
        'name', user.name,
        'gender', user.gender,
        'headimg', user.headimg,
        'city', user.city,
        'province', user.province,
        'country', user.country,
        'isBlock', user.isBlock,
        function(err, obj){
            fn(err, obj);
        });
}
/**
 * 朋友列表user:weight:friends:
 * 有序列表：score为 关系权重
 * value为 userid
 * @param userid
 * @param callback
 *              resp: 加入已经存在 0, 加入不存在 1
 */
exports.addUserFriend = function(userid, weight, user, callback){
    client.auth(config.redis_password);
    var key = 'user:weight:friends:'+userid;
    client.zadd(key, weight, user.id, function (err, resp) {
        callback(err, resp)
    })

}
/**
 * 朋友无序列表user:friends:
 */
exports.addUserSet = function(userid, user, callback){
    client.auth(config.redis_password);
    var key = 'user:friends:'+userid;
    client.sadd(key, user.id, function(err, user){
        callback(err, user);
    });
}
/**
 * 是否是朋友
 * @param userid
 * @param targetid
 * @param callback
 */
exports.isInUserSet = function(userid, targetid, callback){
    client.auth(config.redis_password);
    var key = 'user:friends:'+userid;
    client.sismember(key, targetid, function(err, resp){
        callback(err, resp);
    });
}

exports.addBothUserSet = function(userone, usertwo, callback){
    var ep = new EventProxy();
    ep.bind('error', function(err){
        callback(err);
    });
    ep.all('one', 'two', function(one, two){
        callback(null, one && two);
    });
    client.auth(config.redis_password);
    var key = 'user:friends:'+userone;
    client.sadd(key, usertwo, function(err, res){
        if(err) ep.emit('error', err);
        ep.emit('one', res);
    });
    var key = 'user:friends:'+usertwo;
    client.sadd(key, userone, function(err, res){
        if(err) ep.emit('error', err);
        ep.emit('two', res);
    });

}

exports.addBothWayFriend = function(userone, usertwo, weight, callback){
    var ep = new EventProxy();
        ep.bind('error', function(err){
            callback(err);
        });
        ep.all('one', 'two', function(one, two){
            callback(null, one && two);
        });
    client.auth(config.redis_password);
    var key = 'user:weight:friends:'+userone;
    client.zadd(key, weight, usertwo, function (err, resp) {
        if(err) ep.emit('error', err);
        ep.emit('one', resp);
    });
    var key = 'user:weight:friends:'+usertwo;
    client.zadd(key, weight, userone, function (err, resp) {
        if(err) ep.emit('error', err);
        ep.emit('two', resp);
    });

}
/**
 * 按权重的降序得到友人列表
 * value为 userid
 * @param userid
 * @param callback
 */
exports.getUserFriends = function(userid, callback){
    client.auth(config.redis_password);
    var key = 'user:weight:friends:'+userid;
    client.zrevrange([key, 0, -1], function(err, response){
        callback(err, response);
    })
}
/**
 * 加入积分榜
 * @param actid
 * @param userid
 * @param score
 * @param callback
 */
//TODO: abandoned
exports.addScoreList = function(actid, userid, score, callback){
    client.auth(config.redis_password);
    var key = 'scorelist:'+actid;
    client.zadd(key, score, userid, function(err, resp){
        callback(err, resp);
    })
}
/**
 * 获得积分榜
 * @param actid
 * @param callback
 */
exports.getScoreList = function(actid, end, callback){
    client.auth(config.redis_password);
    var key = 'scorelist:'+actid;
    client.zrevrange([key, 0, end, 'WITHSCORES'], function(err, resp){
        callback(err, resp);
    })
}
/**
 * 加入出席set
 * @param actid
 * @param userid
 * @param callback
 */
exports.addAttendSet = function(actid, userid, callback){
    client.auth(config.redis_password);
    var key = 'actattendset:'+actid;
    client.sadd(key, userid, function(err, resp){
        callback(err, resp);
    });
}
/**
 * 是否已参与
 * @param actid
 * @param userid
 * @param callback
 */
exports.isInAttends = function(actid, userid, callback){
    client.auth(config.redis_password);
    var key = 'actattendset:'+actid;
    client.sismember(key, userid, function(err, resp){
        callback(err, resp);
    })
}
/**
 * 增加出席活动积分
 * @param actid
 * @param userid
 * @param score
 * @param callback
 */
exports.addAttendActScore = function(actid, userid, score, callback){
    client.auth(config.redis_password);
    var key = 'act:'+actid+':user:'+userid;
    client.set(key, score, function (err, obj) {
        callback(err, obj);
    });
}
exports.getAttendActScore = function(actid, userid, callback){
    client.auth(config.redis_password);
    var key = 'act:'+actid+':user:'+userid;
    client.get(key, function (err, obj) {
        callback(err, obj);
    });
}
/**
 * 出席名次
 * @param actid
 * @param userid
 * @param score
 * @param callback
 */
exports.setAttendActNo = function(actid, userid, no, callback){
    client.auth(config.redis_password);
    var key = 'act:'+actid+':user:'+userid+':no';
    client.set(key, no, function (err, obj) {
        callback(err, obj);
    });
}
exports.getAttendActNo = function(actid, userid, callback){
    client.auth(config.redis_password);
    var key = 'act:'+actid+':user:'+userid+':no';
    client.get(key, function (err, obj) {
        callback(err, obj);
    });
}
/**
 * 删除act出席cache
 * @param actid
 * @param callback
 */
exports.delAttendSet = function(actid, callback){
    client.auth(config.redis_password);
    var key = 'actattendset:'+actid;
    client.del(key, function(err, resp){
        callback(err, resp);
    });
}
/**
 * 加入圈子成员cache
 * @param factionid
 * @param userid
 * @param callback
 */
exports.addFactionMember = function(factionid, userid, callback){
    client.auth(config.redis_password);
    var key = 'faction:member:'+factionid;
    client.sadd(key, userid, function(err, user){
        callback(err, user);
    });
}
/**
 * 是否在圈子里
 * @param factionid
 * @param userid
 * @param callback
 */
exports.isInFaction = function(factionid, userid, callback){
    client.auth(config.redis_password);
    var key = 'faction:member:'+factionid;
    client.sismember(key, userid, function(err, resp){
        if(resp == 1){
            callback(err, true);
        }else{
            callback(err, false);
        }
    })
}
